#include "common.h"
#include "alsaSound.h"
#include "videoRecord.h"
#include "udpCommunication.h"

#define UDP_COMMAND_VIDEO_PORT	25300
#define UDP_COMMAND_TYPE_VENC 1000
#define UDP_COMMAND_SUBTYPE_VENC_RC 0
#define UDP_COMMAND_SUBTYPE_VENC_RC2 1

struct MessageStructVencRC
{
	commandPacketHeader header;
	int bitrate;
	int gop;
};

static AlsaSound audio;
static VideoRecord video;
static UdpCommunication udp_cmd_svr;

int main(int argc, char **argv)
{
	MessageStruct msg;
	int rlen;
	audio.startRecord("/dev/hx280_aud" , 600);
	video.startH264Encode(argc , argv);
	udp_cmd_svr.initServer(UDP_COMMAND_VIDEO_PORT);
	audio.startThread();
	while(1)
	{
		video.procOneFrame();
		do
		{
			rlen = udp_cmd_svr.getPacket(&msg , sizeof(msg));
			if(rlen > 0)
			{
				printf("get command packet, len = %d type=%d sub type=%d\n" , rlen , msg.header.commandType , 
					   msg.header.subCommandType);
				if(msg.header.commandType == UDP_COMMAND_TYPE_VENC)
				{
					if(msg.header.subCommandType == UDP_COMMAND_SUBTYPE_VENC_RC)
					{
						if(msg.header.parameterLen == 
						   sizeof(MessageStructVencRC) - sizeof(commandPacketHeader) &&
						   rlen == sizeof(MessageStructVencRC))
						{
							MessageStructVencRC * msgRc = (MessageStructVencRC *)&msg;
							printf("set main stream bitrate to %d gop to %d\n" , msgRc->bitrate , msgRc->gop);
							video.setRc(0 , msgRc->bitrate , msgRc->gop);
						}
					}
					else if(msg.header.subCommandType == UDP_COMMAND_SUBTYPE_VENC_RC2)
					{
						if(msg.header.parameterLen == 
						   sizeof(MessageStructVencRC) - sizeof(commandPacketHeader) &&
						   rlen == sizeof(MessageStructVencRC))
						{
							MessageStructVencRC * msgRc = (MessageStructVencRC *)&msg;
							printf("set sub stream bitrate to %d gop to %d\n" , msgRc->bitrate , msgRc->gop);
							video.setRc(1 , msgRc->bitrate , msgRc->gop);
						}
					}
				}
				fflush(stdout);
			}
		}while(rlen > 0);
	}

	video.stopH264Encode();
	audio.stopRecord();
	return 0;
}


